package com.sto.stoapp.activity.scanner.inquiry;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.adapter.PictureInfoAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.StoTableFieldName;
import com.sto.stoapp.db.manager.PictureQueryManager;
import com.sto.stoapp.entity.PictureInfoEntity;
import com.sto.stoapp.entity.TableFieldInfoEntity;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

public class PictureInquiryActivity extends StoListenerActivity {

	private CheckBox scanningType, scanningDate, codeCheckBox;
	private RadioButton signType, questionType;
	private EditText startTime, endTime;
	private StoHhmEditText code;
	private Button startTimeButton, endTimeButton, inquiryButton;
	private ListView pictureList;

	private List<PictureInfoEntity> infoList = new ArrayList<PictureInfoEntity>();
	private PictureInfoAdapter infoAdapter;

	private int type = EnumTableNames.STATUS_TABLE_SALESMAN_SIGN.ordinal();;
	private static final int SCAN_RESULT = 1;
	private static final int INQUIRY_RESULT = 2;
	private String tableType;
	private String picType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.sto_picture_inquiry);
		String action = getIntent().getStringExtra(HomeBroadAction.BROAD_TYPE);
		this.setTitleBottom(R.string.picture_inquiry, action);

		initWidget();
		initListener();
		tableType = getIntent().getStringExtra(HomeBroadAction.BROAD_TYPE);
		picType = getIntent().getStringExtra("bus");
	}

	// 初始化数据
	private void initWidget() {
		scanningType = (CheckBox) this.findViewById(R.id.scanning_type);
		signType = (RadioButton) this.findViewById(R.id.sign_type);
		questionType = (RadioButton) this.findViewById(R.id.question_type);
		scanningDate = (CheckBox) this.findViewById(R.id.scanning_date);
		startTime = (EditText) this.findViewById(R.id.start_time);
		endTime = (EditText) this.findViewById(R.id.end_time);
		startTimeButton = (Button) this.findViewById(R.id.start_time_button);
		endTimeButton = (Button) this.findViewById(R.id.end_time_button);
		codeCheckBox = (CheckBox) this.findViewById(R.id.code_check_box);
		code = (StoHhmEditText) this.findViewById(R.id.code);
		code.setText("");
		code.requestFocus();
		inquiryButton = (Button) this.findViewById(R.id.inquiry_button);
		pictureList = (ListView) this.findViewById(R.id.picture_list);
	}

	// 监听数据
	private void initListener() {
		scanningType.setChecked(true);
		signType.setChecked(true);
		scanningDate.setChecked(true);
		codeCheckBox.setChecked(true);
		startTime.setText(getCurrentDate());
		endTime.setText(getCurrentDate());

		startTimeButton.setOnClickListener(onClickListener);
		endTimeButton.setOnClickListener(onClickListener);

		signType.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				type = EnumTableNames.STATUS_TABLE_SALESMAN_SIGN.ordinal();
			}
		});

		questionType.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (tableType != null
						&& tableType
								.equals(HomeBroadAction.AVIATION_SCANNER_BROAD))
					type = EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM
							.ordinal();
				else if (picType != null
						&& picType
								.equals(HomeBroadAction.AVIATION_SCANNER_BROAD))
					type = EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM
							.ordinal();
				else
					type = EnumTableNames.STATUS_TABLE_PROBLEM.ordinal();
			}
		});

		inquiryButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				doQuery();
			}
		});
		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onEditClickListener(View v) {
				doQuery();

			}
		});
		pictureList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String itemText = ((TextView) view
						.findViewById(R.id.picture_name)).getText().toString();
				String scanDate = ((TextView) view
						.findViewById(R.id.picture_date)).getText().toString();
				initPopWindow(position, itemText, scanDate);

			}
		});
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			dateSetDialog(v.getId());
		}
	};

	// 获取日期
	@SuppressLint("SimpleDateFormat")
	private String getCurrentDate() {
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				UnifiedStaticType.SIMPLE_DATE_FORMAT);
		String date = sDateFormat.format(new java.util.Date());

		return date;
	}

	// 获取日期的Dialog
	private void dateSetDialog(final int id) {
		final DatePicker datePicker = new DatePicker(this);
		int year = datePicker.getYear();
		int month = datePicker.getMonth();
		int dayOfMonth = datePicker.getDayOfMonth();

		OnDateSetListener callBack = new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {

				int month = monthOfYear + 1;
				String strMonth = null;
				String strDayOfMonth = null;
				if (0 < month && month < 10) {
					strMonth = "0" + month;
				} else {
					strMonth = "" + month;
				}
				if (0 < dayOfMonth && dayOfMonth < 10) {
					strDayOfMonth = "0" + dayOfMonth;
				} else {
					strDayOfMonth = "" + dayOfMonth;
				}
				String date = new StringBuilder().append(year).append("-")
						.append(strMonth).append("-").append(strDayOfMonth)
						.toString();
				if (id == R.id.start_time_button) {
					startTime.setText("");
					startTime.setText(date);

				} else if (id == R.id.end_time_button) {
					endTime.setText("");
					endTime.setText(date);
				}
			}
		};
		DatePickerDialog datePickerDialog = new DatePickerDialog(this,
				callBack, year, month, dayOfMonth);

		datePickerDialog.show();
	}

	// 设置图片信息适配器
	private void setPictureInfoAdapter(String sql, String[] str) {
		try {
			if (infoList.size() > 0)
				infoList.clear();

			if (infoAdapter != null) {
				infoAdapter.notifyDataSetChanged();
			}

			TableFieldInfoEntity infoEntity = new TableFieldInfoEntity();
			infoEntity.setSelectSql(sql);
			infoEntity.setSelectField(str);
			PictureInquiryThread inquiryThread = new PictureInquiryThread(this,
					mHandler, infoEntity);
			inquiryThread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 放大图片显示
	 */
	@SuppressWarnings("deprecation")
	private void initPopWindow(int item, String PictureInfo, String scanDate) {
		try {
			Bitmap bitmap = getBitmapByPath(infoList.get(item).getPictureName()
					.substring(2));
			if (bitmap == null)
				return;

			Display display = getWindowManager().getDefaultDisplay();

			// 加载popupWindow的布局文件
			View contentView = LayoutInflater.from(getApplicationContext())
					.inflate(R.layout.sto_picture_info_popup, null);

			// 设置popupWindow的背景颜色
			contentView.setBackgroundResource(R.drawable.app_bg);
			int width = display.getWidth();
			int height = display.getHeight();
			// 声明一个弹出框
			final PopupWindow popupWindow = new PopupWindow(contentView, width,
					height);
			popupWindow.setFocusable(true);
			popupWindow.showAtLocation(scanningType, Gravity.CENTER, 0, 0);
			TextView pictureInfo = (TextView) contentView
					.findViewById(R.id.picture_info);
			ImageView imageView = (ImageView) contentView
					.findViewById(R.id.image_picture);
			Button close = (Button) contentView
					.findViewById(R.id.close_picture);

			Bitmap rebitmap = Bitmap.createScaledBitmap(bitmap, width - 10,
					height - 83, true);
			String info = "图片详情(" + PictureInfo + ")\n扫描时间:" + scanDate;
			pictureInfo.setText(info);
			close.setText("关闭");
			// 显示图片
			imageView.setImageBitmap(rebitmap);
			imageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					popupWindow.dismiss();
				}
			});
			close.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					popupWindow.dismiss();
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doQuery() {
		if (codeCheckBox.isChecked() && code.getText().toString().length() == 0) {
			Helper.showSoundToast(this, "不能为空", false);
			return;
		}
		if (!scanningType.isChecked() && !scanningDate.isChecked()
				&& !codeCheckBox.isChecked()) {
			Helper.showSoundToast(this, "请选择查询类型", false);
			return;
		}
		String sql = null;
		String[] str = null;
		StoTableFieldName tableFieldName = new StoTableFieldName();
		String ORDER_BY_DATE_AND_TIME_DESC = " order by "
				+ tableFieldName.SCAN_DATE2 + " desc,"
				+ tableFieldName.SCAN_TIME + " desc";
		if (!scanningType.isChecked()) {
			// 扫描日期开启
			if (scanningDate.isChecked()) {
				if (startTime.getText().toString()
						.compareTo(endTime.getText().toString()) < 0) {
					Helper.showSoundToast(PictureInquiryActivity.this,
							"结束时间不能大于开始时间", false);
					return;
				} else if (startTime.length() <= 0 || endTime.length() <= 0) {
					Helper.showSoundToast(PictureInquiryActivity.this,
							"结束时间或开始时间不能为空", false);
					return;
				} else if (code.length() > 0) {
					sql = "select * from "
							+ EnumTableNames.values()[type].getTableName()
							+ " where " + " datetime("
							+ tableFieldName.USER_DEFINED3 + ")"
							+ " between datetime(?) and datetime(?) and "
							+ tableFieldName.BAR_CODE_NUMBER + " = ? and "
							+ tableFieldName.USER_DEFINED4 + " != '' "
							+ ORDER_BY_DATE_AND_TIME_DESC;
					str = new String[] { endTime.getText().toString(),
							startTime.getText().toString(),

							code.getText().toString() };
				} else {
					sql = "select * from "
							+ EnumTableNames.values()[type].getTableName()
							+ " where " + " datetime("
							+ tableFieldName.USER_DEFINED3 + ")"
							+ " between datetime(?) and datetime(?) and "
							+ tableFieldName.USER_DEFINED4 + " != '' "
							+ ORDER_BY_DATE_AND_TIME_DESC;
					str = new String[] { endTime.getText().toString(),
							startTime.getText().toString() };
				}
			}
			// 没有开启扫描日期
			else {
				if (code.length() > 0) {
					sql = "select * from "
							+ EnumTableNames.values()[type].getTableName()
							+ " where " + tableFieldName.BAR_CODE_NUMBER
							+ " = ? and " + tableFieldName.USER_DEFINED4
							+ " != '' " + ORDER_BY_DATE_AND_TIME_DESC;
					str = new String[] { code.getText().toString() };
				} else {
					sql = "select * from "
							+ EnumTableNames.values()[type].getTableName()
							+ " where " + tableFieldName.USER_DEFINED4
							+ " != '' " + ORDER_BY_DATE_AND_TIME_DESC;
					str = new String[] {};
				}
			}
		}

		// 选择签收类型
		else if (signType.isChecked() || questionType.isChecked()) {
			// 扫描日期开启
			if (scanningDate.isChecked()) {
				if (startTime.getText().toString()
						.compareTo(endTime.getText().toString()) < 0) {
					Helper.showSoundToast(PictureInquiryActivity.this,
							"结束时间不能大于开始时间", false);
					return;
				} else if (startTime.length() <= 0 || endTime.length() <= 0) {
					Helper.showSoundToast(PictureInquiryActivity.this,
							"结束时间或开始时间不能为空", false);
					return;
				} else if (code.length() > 0) {
					sql = "select * from "
							+ EnumTableNames.values()[type].getTableName()
							+ " where " + " datetime("
							+ tableFieldName.USER_DEFINED3 + ")"
							+ " between datetime(?) and datetime(?) and "
							+ tableFieldName.BAR_CODE_NUMBER + " = ? and "
							+ tableFieldName.USER_DEFINED4 + " != ''"
							+ ORDER_BY_DATE_AND_TIME_DESC;
					str = new String[] { endTime.getText().toString(),
							startTime.getText().toString(),
							code.getText().toString() };
				} else {
					sql = "select * from "
							+ EnumTableNames.values()[type].getTableName()
							+ " where " + " datetime("
							+ tableFieldName.USER_DEFINED3 + ")"
							+ " between datetime(?) and datetime(?) and "
							+ tableFieldName.USER_DEFINED4 + " != '' "
							+ ORDER_BY_DATE_AND_TIME_DESC;
					str = new String[] { endTime.getText().toString(),
							startTime.getText().toString() };
				}
			}
			// 没有开启扫描日期
			else {
				if (code.length() > 0) {
					sql = "select * from "
							+ EnumTableNames.values()[type].getTableName()
							+ " where " + tableFieldName.BAR_CODE_NUMBER
							+ " = ? and " + tableFieldName.USER_DEFINED4
							+ " != ''" + ORDER_BY_DATE_AND_TIME_DESC;
					str = new String[] { code.getText().toString() };
				} else {
					sql = "select * from "
							+ EnumTableNames.values()[type].getTableName()
							+ " where "

							+ tableFieldName.USER_DEFINED4 + " != ''"
							+ ORDER_BY_DATE_AND_TIME_DESC;
					str = new String[] {};
				}
			}
		} else {
			return;
		}
		setPictureInfoAdapter(sql, str);

	}

	/**
	 * 生成与原图同样大小的Bitmap，不作压缩
	 * 
	 * @param path
	 * @return
	 */
	private Bitmap getBitmapByPath(String path) {
		FileInputStream fis;
		Bitmap bitmap = null;
		try {
			fis = new FileInputStream(path);
			bitmap = BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case SCAN_RESULT:
				code.setText((String) msg.obj);
				doQuery();
				break;
			case INQUIRY_RESULT:
				infoList = (List<PictureInfoEntity>) msg.obj;
				if (infoList != null && infoList.size() != 0) {
					infoAdapter = new PictureInfoAdapter(
							PictureInquiryActivity.this, infoList);
					pictureList.setAdapter(infoAdapter);

					// pictureList.requestFocus();
					// pictureList.setSelection(0);
				} else {
					Helper.showSoundToast(PictureInquiryActivity.this, "查不到数据",
							false);
				}

			default:
				break;
			}
		}

	};

	class PictureInquiryThread extends BaseThread {

		Handler handler;
		TableFieldInfoEntity info;
		Context context;

		PictureInquiryThread(Context context, Handler handler,
				TableFieldInfoEntity info) {
			super(context);
			this.handler = handler;
			this.info = info;
			this.context = context;
			showDialog();
		}

		@Override
		public void run() {
			super.run();
			PictureQueryManager pictureManager = new PictureQueryManager(
					context);
			try {
				List<PictureInfoEntity> infos = pictureManager.queryAll(
						context, info);
				Message msg = new Message();
				msg.what = INQUIRY_RESULT;
				msg.obj = infos;
				handler.sendMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				cancelDialog();
			}
		}

	}

	@Override
	public void onScanResults(String str) {
		if (str != null && str.length() != 0) {
			Message msg = new Message();
			msg.what = SCAN_RESULT;
			msg.obj = str.trim();
			mHandler.sendMessage(msg);
		}
	}

	@Override
	protected void handlerScanData(String scanData) {
		code.setText(scanData);
		SoundManager.getInstance(PictureInquiryActivity.this)
				.playSuccessSound();

	}
}
